package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.dao.ShoppingCartMapper;
import com.itheima.domian.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public void add(ShoppingCart shoppingCart) {
        //查询购物车是否含有这商品 如果没有 就添加 有的话就将数量加一
        ShoppingCart one = this.getOne(Wrappers.<ShoppingCart>lambdaQuery().eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId()).eq(ShoppingCart::getUserId, BaseContext.getId()));

        if (one == null) {
            //将数据添加到购物车
            shoppingCart.setUserId(BaseContext.getId());
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            return;
        }
        one.setNumber(one.getNumber() + 1);
        this.updateById(one);
    }

    //删除 数据
    @Override
    public void sub(ShoppingCart shoppingCart) {
        //分析 进行删除时 先查询数据 看看 数量是不是最后一个
        // 如果是 最后一个 就将该商品删除 如果不是就修改数据减一
        ShoppingCart one = this.getOne(Wrappers.<ShoppingCart>lambdaQuery().eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId()).eq(ShoppingCart::getUserId, BaseContext.getId()));

        if (one.getNumber() == 1) {
            this.remove(Wrappers.<ShoppingCart>lambdaQuery().eq(ShoppingCart::getId, one.getId()));
           /* this.remove(Wrappers.<ShoppingCart>lambdaQuery().eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                    .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId()).eq(ShoppingCart::getUserId, BaseContext.getId()));
     */
        }
        //不是最后一个就 将number减1
        one.setNumber(one.getNumber() - 1);
        this.updateById(one);

    }
    //清楚购物车

    @Override
    public void delete() {
        //根据用户名id进行删除 全部的数据
        this.remove(Wrappers.<ShoppingCart>lambdaQuery().eq(ShoppingCart::getUserId, BaseContext.getId()));

    }
}
